package com.cdks.wuxiu.api.controller;

import com.cdks.wuxiu.api.model.param.VoiceGetInfoParam;
import com.cdks.wuxiu.api.model.param.VoicePlayParam;
import com.cdks.wuxiu.api.model.param.VoiceRewardParam;
import com.cdks.wuxiu.api.service.UserService;
import com.cdks.wuxiu.api.service.VoiceService;
import com.cdks.wuxiu.common.model.api.ApiResult;
import com.cdks.wuxiu.entity.mysql.UserBaseInfo;
import com.cdks.wuxiu.entity.mysql.UserLoginInfo;

import cn.hutool.json.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;


@Api(tags = "语音秀")
@Slf4j
@RestController
@RequestMapping("/voice")
public class VoiceController {
    @Resource
    private VoiceService voiceService;
    @Resource
    private UserService userService;    

    
    @ApiOperation("查询用户视频信息")
    @PostMapping("/getInfo")
    public ApiResult<Object> getInfo(@RequestBody @Valid VoiceGetInfoParam param) {
        return ApiResult.success(voiceService.getVoiceInfo(param.getVoiceId()));
    }

    @ApiOperation("播放语音")
    @PostMapping("/play")
    public ApiResult<Object> play(@RequestBody @Valid VoicePlayParam param) {
        String udid  = param.getUdid();
        UserBaseInfo userInfo  = param.getUserInfo();

        if (userInfo == null)
        {
            if (param.getCount() > 5) {
                JSONObject json  = new JSONObject();
                json.set("scheme", "xinsu://account/login");
                
                return ApiResult.failed(11, "查看更多精彩内容，请先登录", json);  
            }

            if (udid == null)
            {
                return ApiResult.success();
            }
        }

        if ((udid == null) && (param.getUserId() != null)) {
            UserLoginInfo loginInfo  = userService.getUserLoginInfo(param.getUserId());
            udid  = loginInfo.getUdid();
        }

        //记录播放数据
        voiceService.play(param.getUserId(), udid, param.getVoiceId());

        return ApiResult.success();
    }
    
    @ApiOperation("打赏")
    @PostMapping("/reward")
    public ApiResult<Object> reward(@RequestBody @Valid VoiceRewardParam param) {
        //扣费
        int ret  = voiceService.charge(param.getVoiceId(), param.getUserInfo(), param.getCost());
        if (ret < 0)
        {
            JSONObject json  = new JSONObject();
            json.set("scheme", "xinsu://bean/recharge");

            return ApiResult.failed(-10, "账户余额不足，请先充值", json);
        }

        return ApiResult.success();
    }    
}
